import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'
Vue.use(VueRouter)
const originPush = VueRouter.prototype.push
const originreplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location,okCallBack,errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    // 统一处理错误提示
    originPush.call(this, location).catch(() => { })
  } else {
    originPush.call(this,location,okCallBack,errCallBack)
  }
}

VueRouter.prototype.replace = function (location,okCallBack,errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    // 统一处理错误提示
    originreplace.call(this, location).catch(() => { })
  } else {
    originreplace.call(this,location,okCallBack,errCallBack)
  }
}

const whiteList=[
  "home",
  "login",
  "register",
  "search",
  "detail",
  "addcartsuccess",
  "shopcart",
]
const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition
      } else {
        return { x: 0, y: 0 }
      }
    },
})
router.beforeEach((to,from,next)=>{
  if(whiteList.includes(to.name)||store.state.user.userInfo.token){
    next()
    return
  }
  next({
    name:"login",
    query:{
      redirect:to.path
    }
  })
})
export default router